package com.leyou.user.interceptors;

import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.user.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
public class PrivilegeInterceptor implements HandlerInterceptor {

    private JwtProperties prope;

    public PrivilegeInterceptor(JwtProperties prope) {
        this.prope = prope;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            String token = request.getHeader(prope.getApp().getHeaderName());

            Payload<AppInfo> payload = JwtUtils.getInfoFromToken(token, prope.getPublicKey(), AppInfo.class);

            AppInfo info = payload.getInfo();

            List<Long> targetList = info.getTargetList();
            if (!targetList.contains(prope.getApp().getId())){
                // 没有访问权限，抛出异常
                log.error("请求者没有访问本服务的权限！");
            }
            log.info("服务{}正在请求资源:{}", info.getServiceName(), request.getRequestURI());
            return true;
        } catch (Exception e) {
            log.error("服务访问被拒绝,token认证失败!");
            return false;
        }
    }
}
